カウンターのソースはこんな感じ。
class webCounter { private $m_hMemory; private $m_szFilename; private $m_nLastError; private $m_nSzLastError; private $m_nExpire; private $m_nCounterLength; function __construct($filename) { $this->m_hMemory = new memcached(); $this->m_szFilename = $filename; $this->m_nLastError = 0; $this->m_nSzLastError = ""; $this->m_nExpire = 24*60*60; $this->m_nCounterLength = 8; } function __destruct() { unset($this->hMemory); } // ----------------------------------------------------------------- // input : key // output : none // return : false when failed. // othrwise return array. // array(0) = web counter. // array(1) = count to key access. // ----------------------------------------------------------------- public function getCount($szUniqKey) { $ret = $this->m_hMemory->getServerList(); if ( empty($ret) ) { $ret = $this->m_hMemory->addServer("localhost", 11211); if ( $ret !== true ) { $this->m_nLastError = $this->m_hMemory->getResultCode(); $this->m_nSzLastError = $this->m_hMemory->getResultMessage(); return(false); } } $value = $this->m_hMemory->get($szUniqKey); if ( $value !== false ) { $count = $this->currentCount(); return($count); } $ret = $this->m_hMemory->set($szUniqKey, 1, $this->m_nExpire); if ( $ret !== true ) { } $count = $this->incleseWebCounter(); return($count); } private function incleseWebCounter() { $fp = fopen($this->m_szFilename, 'r+'); if ($fp) { if (flock($fp, LOCK_EX) === false) { return(0); } } $counter = (int) fgets($fp, $this->m_nCounterLength); $counter++; rewind($fp); if (fwrite($fp, $counter) === FALSE) { flock ($fp, LOCK_UN); fclose ($fp); return(0); } flock ($fp, LOCK_UN); fclose ($fp); $fotmat = sprintf("%%0%dd", $this->m_nCounterLength); $counter = sprintf($fotmat, $counter); return($counter); } private function currentCount() { $fp = fopen($this->m_szFilename, 'r'); if ($fp) { if (flock($fp, LOCK_SH) === false) { return(0); } } $counter = (int) fgets($fp, $this->m_nCounterLength); flock ($fp, LOCK_UN); fclose ($fp); // $fotmat = sprintf("%%0%dd", $this->m_nCounterLength); // $counter = sprintf($fotmat, $counter); return($counter); } }これをこんなカンジで呼び出します。 $counter_lenght = 8; $webCounter = new webCounter($gblSzCounter); $counter = $webCounter->getCount($_SERVER["REMOTE_ADDR"]); $fotmat = sprintf("%%0%dd", $counter_lenght); $counter = sprintf($fotmat, $counter); echo 'Counter: ' . $counter ;$gblSzCounterにはカウンターファイル名称が格納されています。
TOC
|